<template>
  <v-dialog
    v-model="dialogFormVisible"
    max-width="800px"
    persistent
  >
    <v-card class="rounded-xl">
      <v-card-title class="d-flex align-center">
        <span>{{ title }}</span>
        <v-spacer></v-spacer>
        <v-btn
          icon="mdi-close"
          variant="text"
          @click="close"
        ></v-btn>
      </v-card-title>

      <v-card-text>
        <v-file-input
          ref="fileInputRef"
          v-model="selectedFiles"
          label="选择Excel文件"
          accept=".xls,.xlsx"
          prepend-icon="mdi-file-excel"
          variant="outlined"
          :rules="fileRules"
          :loading="uploading"
          @change="handleFileChange"
          @click:clear="clearFiles"
        >
          <template v-slot:selection="{ fileNames }">
            <template v-for="fileName in fileNames" :key="fileName">
              <v-chip
                color="primary"
                size="small"
                class="me-2"
              >
                {{ fileName }}
              </v-chip>
            </template>
          </template>
        </v-file-input>

        <!-- 上传区域 -->
        <v-card
          v-if="!selectedFiles?.length"
          class="mt-4 pa-8 text-center"
          variant="outlined"
          style="border: 2px dashed #ccc;"
          @drop="handleDrop"
          @dragover.prevent
          @dragenter.prevent
        >
          <v-icon size="48" color="grey">mdi-cloud-upload</v-icon>
          <div class="text-h6 mt-2">拖拽文件到此处</div>
          <div class="text-body-2 text-grey">或点击上方选择文件</div>
          <div class="text-caption text-grey mt-2">
            支持 .xls 和 .xlsx 格式，文件大小不超过 5MB
          </div>
        </v-card>

        <!-- 上传进度 -->
        <v-card
          v-if="uploading"
          class="mt-4 pa-4"
          variant="outlined"
        >
          <div class="d-flex align-center">
            <v-icon color="primary" class="me-2">mdi-upload</v-icon>
            <span>正在上传...</span>
            <v-spacer></v-spacer>
            <span>{{ uploadProgress }}%</span>
          </div>
          <v-progress-linear
            v-model="uploadProgress"
            color="primary"
            class="mt-2"
          ></v-progress-linear>
        </v-card>

        <!-- 上传结果 -->
        <v-alert
          v-if="uploadResult"
          :type="uploadResult.type"
          class="mt-4"
          closable
          @click:close="uploadResult = null"
        >
          {{ uploadResult.message }}
        </v-alert>
      </v-card-text>

      <v-card-actions class="px-6 pb-4">
        <v-btn
          color="primary"
          variant="outlined"
          @click="downloadExcelTemplate"
        >
          <v-icon start>mdi-download</v-icon>
          下载模板
        </v-btn>
        <v-spacer></v-spacer>
        <v-btn
          variant="outlined"
          @click="close"
        >
          关闭
        </v-btn>
        <v-btn
          color="primary"
          :disabled="!selectedFiles?.length || uploading"
          :loading="uploading"
          @click="handleUpload"
        >
          <v-icon start>mdi-upload</v-icon>
          上传
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script setup>
import { ref, getCurrentInstance } from 'vue';
import { doDownloadTemplate, doImportExcel } from '@/api/system/options/SysOptionsManagement';
import { isNull } from '@/utils/validate';
import { random } from '@/utils';
import { useMessage } from '@/composables/useMessage';

const { proxy } = getCurrentInstance();
const { success: showSuccess, error: showError, warning: showWarning } = useMessage();

// 响应式数据
const dialogFormVisible = ref(false);
const title = ref('导入Excel');
const selectedFiles = ref([]);
const uploading = ref(false);
const uploadProgress = ref(0);
const uploadResult = ref(null);

// 组件引用
const fileInputRef = ref();

// 文件验证规则
const fileRules = [
  value => {
    if (!value || !value.length) return true;
    const file = value[0];
    const validTypes = ['application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
    const validExtensions = ['.xls', '.xlsx'];
    const hasValidExtension = validExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
    
    if (!validTypes.includes(file.type) && !hasValidExtension) {
      return '只能上传 .xls 或 .xlsx 格式的文件';
    }
    
    if (file.size > 5 * 1024 * 1024) {
      return '文件大小不能超过 5MB';
    }
    
    return true;
  }
];

// 暴露方法
defineExpose({
  show
});

// 事件定义
const emit = defineEmits(['fetchData']);

/**
 * 显示对话框
 */
function show() {
  dialogFormVisible.value = true;
  resetUpload();
}

/**
 * 关闭对话框
 */
function close() {
  dialogFormVisible.value = false;
  resetUpload();
}

/**
 * 重置上传状态
 */
function resetUpload() {
  selectedFiles.value = [];
  uploading.value = false;
  uploadProgress.value = 0;
  uploadResult.value = null;
}

/**
 * 清除文件
 */
function clearFiles() {
  selectedFiles.value = [];
  uploadResult.value = null;
}

/**
 * 文件选择变化
 */
function handleFileChange(files) {
  if (files && files.length > 0) {
    uploadResult.value = null;
  }
}

/**
 * 拖拽文件处理
 */
function handleDrop(event) {
  event.preventDefault();
  const files = Array.from(event.dataTransfer.files);
  
  if (files.length > 0) {
    const file = files[0];
    
    // 验证文件
    const validExtensions = ['.xls', '.xlsx'];
    const hasValidExtension = validExtensions.some(ext => file.name.toLowerCase().endsWith(ext));
    
    if (!hasValidExtension) {
      showWarning('只能上传 .xls 或 .xlsx 格式的文件');
      return;
    }
    
    if (file.size > 5 * 1024 * 1024) {
      showWarning('文件大小不能超过 5MB');
      return;
    }
    
    selectedFiles.value = [file];
    uploadResult.value = null;
  }
}

/**
 * 下载模板
 */
function downloadExcelTemplate() {
  try {
    doDownloadTemplate();
    showSuccess('模板下载已开始');
  } catch (error) {
    console.error('下载模板失败:', error);
    showError('下载模板失败');
  }
}

/**
 * 上传文件
 */
async function handleUpload() {
  if (!selectedFiles.value || selectedFiles.value.length === 0) {
    showWarning('请先选择要上传的文件');
    return;
  }

  const file = selectedFiles.value[0];
  uploading.value = true;
  uploadProgress.value = 0;
  uploadResult.value = null;

  try {
    // 模拟进度更新
    const progressTimer = setInterval(() => {
      if (uploadProgress.value < 90) {
        uploadProgress.value += random(5, 15);
      }
    }, 200);

    // 创建FormData
    const formData = new FormData();
    formData.append('file', file);

    // 执行上传
    const response = await doImportExcel(formData);
    
    // 清除进度定时器
    clearInterval(progressTimer);
    uploadProgress.value = 100;

    // 显示结果
    uploadResult.value = {
      type: 'success',
      message: response.msg || '导入成功'
    };

    showSuccess(response.msg || '导入成功');
    
    // 通知父组件刷新数据
    emit('fetchData');
    
    // 延迟关闭对话框
    setTimeout(() => {
      close();
    }, 2000);

  } catch (error) {
    console.error('上传失败:', error);
    
    uploadResult.value = {
      type: 'error',
      message: error.message || '导入失败'
    };
    
    showError(error.message || '导入失败');
  } finally {
    uploading.value = false;
  }
}
</script>

<style scoped>
.v-card-title {
  font-weight: 600;
}

.v-file-input :deep(.v-field__input) {
  cursor: pointer;
}
</style>
